package com.livi.security.service.sys.impl;

import com.livi.security.mapper.sys.SysUserMapper;
import com.livi.security.model.commom.BaseResponse;
import com.livi.security.model.sys.SysUser;
import com.livi.security.service.sys.UserService;
import com.livi.security.util.PasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author Livi Luo
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    SysUserMapper sysUserMapper;

    @Override
    public BaseResponse get(Integer userId) {
        SysUser one = sysUserMapper.selectByPrimaryKey(userId);
        return new BaseResponse<>("load success", one);
    }

    @Override
    public BaseResponse getList() {
        List<SysUser> list = sysUserMapper.selectAll();
        return new BaseResponse<List<SysUser>>("load success", list);
    }

    @Override
    public BaseResponse add(SysUser record, Integer currentUser) {
        SysUser one = sysUserMapper.selectByAccount(record.getAccount());
        if (one != null)
            return new BaseResponse(false, "user exist");
        String password = PasswordEncoder.generateEncode(record.getPassword());
        record.setPassword(password);
        record.setCreateBy(currentUser);
        record.setUpdateBy(currentUser);
        record.setCreateTime(new Date());
        record.setUpdateTime(new Date());
        sysUserMapper.insertSelective(record);
        return new BaseResponse<SysUser>("create success", record);
    }

    @Override
    public BaseResponse update(SysUser record, Integer currentUser) {
        record.setUpdateBy(currentUser);
        record.setUpdateTime(new Date());
        sysUserMapper.updateByPrimaryKeySelective(record);
        return new BaseResponse<>(true, "update success");
    }

    @Override
    public BaseResponse delete(Integer userId) {
        sysUserMapper.deleteByPrimaryKey(userId);
        return new BaseResponse<>(true, "delete success");
    }

}
